package com.fanxuankai.boot.apollo.openapi.autoconfigure;

import com.ctrip.framework.apollo.openapi.client.ApolloOpenApiClient;
import com.fanxuankai.boot.apollo.openapi.component.ApolloConfigPublisher;
import com.fanxuankai.boot.apollo.openapi.component.ApolloConfigSynchronizer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

/**
 * @author fanxuankai
 */
@EnableConfigurationProperties({ApolloOpenApiProperties.class,
        ApolloConfigSyncProperties.class, ApolloConfigPublishProperties.class})
public class ApolloAutoConfiguration {
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty({ApolloOpenApiProperties.PORTAL_URL, ApolloOpenApiProperties.TOKEN})
    public ApolloOpenApiClient apolloOpenApiClient(ApolloOpenApiProperties properties) {
        ApolloOpenApiClient.ApolloOpenApiClientBuilder builder = new ApolloOpenApiClient.ApolloOpenApiClientBuilder();
        builder.withPortalUrl(properties.getPortalUrl())
                .withToken(properties.getToken());
        if (properties.getConnectTimeout() != null) {
            builder.withConnectTimeout(properties.getConnectTimeout());
        }
        if (properties.getReadTimeout() != null) {
            builder.withReadTimeout(properties.getReadTimeout());
        }
        return builder.build();
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnBean({ApolloOpenApiClient.class})
    @ConditionalOnProperty(ApolloConfigSyncProperties.ENABLED)
    public ApolloConfigSynchronizer apolloConfigSynchronizer(ApolloOpenApiClient client,
                                                             ApolloOpenApiProperties properties,
                                                             ApolloConfigSyncProperties syncProperties) {
        return new ApolloConfigSynchronizer(client, properties, syncProperties);
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnBean({ApolloOpenApiClient.class})
    @ConditionalOnProperty(ApolloConfigPublishProperties.ENABLED)
    public ApolloConfigPublisher apolloConfigPublisher(ApolloOpenApiClient client,
                                                       ApolloOpenApiProperties properties,
                                                       ApolloConfigPublishProperties publishProperties) {
        return new ApolloConfigPublisher(client, properties, publishProperties);
    }
}
